package com.fz.us.oa.web.controller.com;

import com.fz.us.admin.company.entity.Admin;
import com.fz.us.admin.company.service.AdminService;
import com.fz.us.admin.base.bean.BaseEnumManager;
import com.fz.us.admin.company.entity.TaskEntity;
import com.fz.us.admin.company.entity.User;
import com.fz.us.admin.company.service.DutyService;
import com.fz.us.admin.company.service.TaskEntityService;
import com.fz.us.admin.company.service.UserService;
import com.fz.us.oa.core.entity.com.AllChange;
import com.fz.us.oa.core.entity.com.PersonnelInfo;
import com.fz.us.oa.core.entity.com.Quit;
import com.fz.us.oa.core.entity.common.FileManage;
import com.fz.us.oa.core.service.com.AllChangeService;
import com.fz.us.oa.core.service.com.PersonnelInfoService;
import com.fz.us.oa.core.service.com.QuitService;
import com.fz.us.oa.core.service.common.FileManagerService;
import com.fz.us.oa.web.controller.BaseController;
import com.fz.us.oa.web.shiro.bind.annotation.CurrentUser;
import com.google.common.collect.Lists;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by ZhuChunXiao on 2017/7/18.
 */
@Controller
@RequestMapping(value = "/com/quit")
public class QuitController extends BaseController {
    private static final long serialVersionUID = -2984631192148504521L;

    @Autowired
    private QuitService quitService;
    @Autowired
    private PersonnelInfoService personnelInfoService;
    @Autowired
    private AllChangeService allChangeService;
    @Autowired
    private UserService userService;
    @Autowired
    private AdminService adminService;
    @Autowired
    private TaskEntityService taskEntityService;
    @Autowired
    private DutyService dutyService;
    @Autowired
    private FileManagerService fileManagerService;


    /**
     * 新建，编辑页面
     */
    @RequestMapping(value = "input", method = RequestMethod.GET, produces = MediaType.TEXT_HTML_VALUE)
    public String input(@CurrentUser User user, Model model,String keyId,String parentId,String draft,String index,String todo,String remind,String record) {
        if (StringUtils.isNotEmpty(keyId)){
            String fileId ="";
            Quit quit=quitService.get(keyId);
            if(quit.getFile() != null && quit.getFile().size()>0){
                for(FileManage f:quit.getFile()){
                    fileId+=f.getId()+",";
                }
            }
            model.addAttribute("keyId", keyId);
            model.addAttribute("fileId", fileId);
            model.addAttribute("quit", quit);
        }
        PersonnelInfo personnelInfo=personnelInfoService.get(parentId);
        model.addAttribute("parentId", parentId);
        model.addAttribute("personnelInfo", personnelInfo);
        model.addAttribute("draft", draft);
        model.addAttribute("index", index);
        model.addAttribute("todo", todo);
        model.addAttribute("remind", remind);
        model.addAttribute("record", record);
        return "/com/quit_input";
    }

    /**
     * 只读页面
     */
    @RequestMapping(value = "read", method = RequestMethod.GET, produces = MediaType.TEXT_HTML_VALUE)
    public String read(@CurrentUser User user, Model model,String keyId,String draft,String index,String todo,String remind,String record) {
        if(StringUtils.isNotEmpty(keyId)) {
            String fileId ="";
            Quit quit=quitService.get(keyId);
            if(quit.getFile() != null && quit.getFile().size()>0){
                for(FileManage f:quit.getFile()){
                    fileId+=f.getId()+",";
                }
            }
            TaskEntity taskEntity = taskEntityService.getInfoByKeyId(keyId);
            int stepNo = taskEntity.getStepNo();
            String isEdit =  isEdit(keyId);
            model.addAttribute("fileId", fileId);
            model.addAttribute("isEdit", isEdit);
            model.addAttribute("quit", quit);
            model.addAttribute("stepNo", stepNo);
        }
        model.addAttribute("keyId", keyId);
        model.addAttribute("draft", draft);
        model.addAttribute("index", index);
        model.addAttribute("todo", todo);
        model.addAttribute("remind", remind);
        model.addAttribute("record", record);
        return "/com/quit_read";
    }

    /**
     * 从异动总汇进入只读页面
     */
    @RequestMapping(value = "toRead",method = RequestMethod.GET,produces = MediaType.TEXT_HTML_VALUE)
    public String toRead(@CurrentUser User user, Model model,String allChangeId,String keyId,String draft,String index,String todo,String remind,String record){
        AllChange allChange=allChangeService.get(allChangeId);
        Quit quit=allChange.getQuit();
        String fileId ="";
        if(quit.getFile() != null && quit.getFile().size()>0){
            for(FileManage f:quit.getFile()){
                fileId+=f.getId()+",";
            }
        }
        TaskEntity taskEntity = taskEntityService.getInfoByKeyId(quit.getId());
        int stepNo = taskEntity.getStepNo();
        String isEdit =  isEdit(quit.getId());
        model.addAttribute("fileId", fileId);
        model.addAttribute("isEdit", isEdit);
        model.addAttribute("quit", quit);
        model.addAttribute("stepNo", stepNo);
        model.addAttribute("keyId", keyId);
        model.addAttribute("draft", draft);
        model.addAttribute("index", index);
        model.addAttribute("todo", todo);
        model.addAttribute("remind", remind);
        model.addAttribute("record", record);

        return "/com/quit_read";
    }

    /**
     * 保存Model操作
     */
    public Quit saveModel(User user, String keyId, String parentId, String type, String reason,
                          String fileIds, String date, String remarks) throws ParseException {
        Quit quit=null;
        if(org.apache.commons.lang.StringUtils.isBlank(keyId)){
            quit=new Quit();
            quit.setCreater(user);
            quit.setCompany(user.getCompany());
            quit.setName("离职申请");
        }else{
            quit=quitService.get(keyId);
        }
        if(org.apache.commons.lang.StringUtils.isNotEmpty(parentId)){
            quit.setPersonnelInfo(personnelInfoService.get(parentId));
        }
        if(org.apache.commons.lang.StringUtils.isNotEmpty(type)){
            quit.setType(Integer.parseInt(type));
        }
        if(org.apache.commons.lang.StringUtils.isNotEmpty(reason)){
            quit.setReason(reason);
        }
        List<FileManage> fileManageList = Lists.newArrayList();
        if(StringUtils.isNotEmpty(fileIds)){
            for(String f:fileIds.split(",")){
                fileManageList.add(fileManagerService.get(f.trim()));
            }
        }
        quit.setFile(fileManageList);
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
        if(org.apache.commons.lang.StringUtils.isNotEmpty(date)){
            quit.setDate(sdf.parse(date));
        }
        if(org.apache.commons.lang.StringUtils.isNotEmpty(remarks)){
            quit.setRemarks(remarks);
        }

        return quit;
    }

    /**
     * 保存操作
     */
    @RequestMapping(value = "save", method = RequestMethod.POST)
    public Object save(@CurrentUser User user,
                       @RequestParam(required = false) String keyId,
                       String parentId,
                       String type,
                       String reason,
                       String fileIds,
                       String date,
                       String remarks) throws ParseException {

        Map<String,Object> rMap=new HashMap<String,Object>();
        Quit quit=saveModel(user, keyId, parentId, type, reason, fileIds, date, remarks);

        if(StringUtils.isNotEmpty(keyId)){
            quitService.update(quit);
            rMap.put("message", "更新成功");
        } else {
            quitService.save(quit, "com.fz.us.oa.core.entity.com.Quit");
            rMap.put("message", "保存成功");
        }
        rMap.put("state", "1");
        rMap.put("keyId", keyId);
        return ajaxJson(rMap);
    }

    /**
     * 提交操作
     */
    @RequestMapping(value = "submit", method = RequestMethod.POST)
    public Object submit(@CurrentUser User user,
                         @RequestParam(required = false) String keyId,
                         String parentId,
                         String type,
                         String reason,
                         String fileIds,
                         String date,
                         String remarks,
                         String curDutyId,
                         String comment) throws ParseException {

        Map<String, Object> rMap = new HashMap<String, Object>();
        Quit quit=saveModel(user,keyId,parentId,type,reason,fileIds,date,remarks);

        if (StringUtils.isNotEmpty(keyId)) {
            quitService.approve(quit, dutyService.get(curDutyId), comment);
        } else {
            quitService.commit(quit, "com.fz.us.oa.core.entity.com.Quit", dutyService.get(curDutyId));
        }

        //新建异动总汇表
        AllChange allChange=new AllChange();
        allChange.setType("3");
        allChange.setQuit(quit);
        allChange.setPersonnelInfo(personnelInfoService.get(parentId));
        allChange.setName("离职申请");
        allChange.setCreater(user);
        allChange.setCompany(user.getCompany());
        allChange.setIsFinished("0");
        allChangeService.commit(allChange, "com.fz.us.oa.core.entity.com.AllChange", dutyService.get(curDutyId));

        quit.setAllChange(allChange);
        quitService.update(quit);

        if(quit.getProcessState().name().equals("Finished")){
            doFinished(quit,parentId);
        }

        rMap.put("message", "提交成功");
        rMap.put("state", "1");
        rMap.put("keyId", keyId);
        return ajaxJson(rMap);
    }

    //审批
    @RequestMapping(value = "approve", method = RequestMethod.POST)
    public Object approve(@CurrentUser User user, String keyId,  String curDutyId, String comment, String parentId){
        Map<String,Object> rMap=new HashMap<String,Object>();
        Quit quit = quitService.get(keyId);
        quitService.approve(quit, dutyService.get(curDutyId), comment);

        //归档后...
        if(quit.getProcessState().name().equals("Finished")){
            doFinished(quit,parentId);
        }
        rMap.put("message","提交成功");
        rMap.put("state","1");
        rMap.put("keyId", keyId);
        return ajaxJson(rMap);
    }

    public void doFinished(Quit quit,String parentId){
        //完成总汇表
        AllChange allChange=quit.getAllChange();
        allChange.setIsFinished("1");
        allChangeService.update(allChange);

        //修改人事信息表 是否离职
        PersonnelInfo personnelInfo=personnelInfoService.get(parentId);
        personnelInfo.setQuit(true);
        personnelInfoService.update(personnelInfo);

        //注销登录权限
        User user1=personnelInfo.getUser();
        user1.setState(BaseEnumManager.StateEnum.Delete);
        userService.saveEntity(user1);
        Admin admin=adminService.get(user1.getAdminId());
        admin.setIsAccountLocked(true);
    }

    /**
     * 退回
     * @return
     */
    @RequestMapping(value = "back", method = RequestMethod.POST)
    public Object back(@CurrentUser User user, String keyId,String curDutyId, String comment) {
        if (StringUtils.isNotEmpty(keyId)) {
            Quit quit = quitService.get(keyId);
            quitService.back(quit, dutyService.get(curDutyId), comment);
        }
        Map<String,Object> rMap=new HashMap<String,Object>();
        rMap.put("message","退回成功");
        rMap.put("state","1");
        rMap.put("keyId", keyId);
        return ajaxJson(rMap);
    }
    /**
     * 否决
     * @return
     */
    @RequestMapping(value = "deny", method = RequestMethod.POST)
    public Object deny(@CurrentUser User user, String keyId,String curDutyId, String comment) {
        if (StringUtils.isNotEmpty(keyId)) {
            Quit quit = quitService.get(keyId);
            quitService.deny(quit, dutyService.get(curDutyId), comment);
        }
        Map<String,Object> rMap=new HashMap<String,Object>();
        rMap.put("message","否决成功");
        rMap.put("state","1");
        rMap.put("keyId", keyId);
        return ajaxJson(rMap);
    }

}
